package com.xbongbong.paas.business.rule;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.pojo.BusinessRulesPoJo;
import com.xbongbong.paas.pojo.dto.InactiveRuleByDeleteBatchDTO;
import com.xbongbong.paas.pojo.dto.InactiveRuleDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.form.pojo.vo.FormBusinessRuleVO;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;


/**
 * @author: wufeng
 * @date: 2018/12/28 16:42
 * @desrcption: 表单数据失效规则
 */
@Component
public class FormDataInactiveRuleByDeleteBatchHelp {

    private static final Logger LOG = LoggerFactory.getLogger(FormDataInactiveRuleByDeleteBatchHelp.class);

    @Resource
    @Lazy
    private FormDataInactiveRuleHelp formDataInactiveRuleHelp;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private BusinessRuleUserPermissionHelp businessRuleUserPermissionHelp;
    @Resource
    private BusinessRuleInfoService businessRuleInfoService;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private IndexTypeModel indexTypeModel;

    @Async(value = "inactiveRuleThreadPool")
    public void inactiveRuleByDeleteBatch(InactiveRuleByDeleteBatchDTO inactiveRuleByDeleteBatchDTO) throws XbbException{
        try {
            List<Long> dataIdList = inactiveRuleByDeleteBatchDTO.getFormDataIdList();
            String corpid = inactiveRuleByDeleteBatchDTO.getCorpid();
            if (businessRuleUserPermissionHelp.validateUsePermission(corpid)) {
                // 非旗舰版直接返回
                LOG.error("not have businessRule permission");
                return;
            }
            Long formId = inactiveRuleByDeleteBatchDTO.getFormId();
            FormBusinessRuleVO businessRuleVO = businessRuleInfoService.get(corpid, formId, inactiveRuleByDeleteBatchDTO.getBusinessType(), inactiveRuleByDeleteBatchDTO.getSaasMark(), 0);
            List<BusinessRulesPoJo> businessRuleList = businessRuleVO.getBusinessRule();
            if (CollectionsUtil.isEmpty(businessRuleList)) {
                return;
            }
            if (Objects.isNull(businessRuleVO.getExcess()) || businessRuleVO.getExcess() > 0) {
                return;
            }
            if (businessRuleVO.getFormulaLimit()) {
                return;
            }
            //解析查询条件
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("formId",formId));
            boolQueryBuilder.filter(termsQuery(StringConstant.DATA_ID, dataIdList));
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            // 排序
            sourceBuilder.sort(new FieldSortBuilder(FieldTypeEnum.UPDATETIME.getAlias()).order(SortOrder.DESC));
            sourceBuilder.query(boolQueryBuilder);
            IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, inactiveRuleByDeleteBatchDTO.getBusinessType(), inactiveRuleByDeleteBatchDTO.getSaasMark());;;
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, indexTypeEnum.getType()));
            List<PaasFormDataEntityExt> list = paasEsModel.list(sourceBuilder, indexTypeEnum, new ArrayList<>(), 1, dataIdList.size());
            Set<Long> parentIdList = new HashSet<>();
            list.forEach(item->{
                parentIdList.add(item.getDataId());
            });
            Integer businessType = inactiveRuleByDeleteBatchDTO.getBusinessType();
            PaasFormExplainEntity paasFormExplainEntity = proFormHelp.getExplainEntity(corpid, formId, businessType);
            // 获取子表单数据
            Map<Long, JSONObject> formDataMap = paasFormSubDataModel.getSubDataMap(corpid, inactiveRuleByDeleteBatchDTO.getSaasMark(), businessType, formId, parentIdList, 1, PaasConstant.SUB_DATA_PAGE_NUM, DelEnum.DELETE_SUBFORM.getDel());

            List<FieldAttrEntity> explainList = JSON.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
            for (PaasFormDataEntityExt paasFormDataEntityExt: list) {
                JSONObject jsonObject = formDataMap.get(paasFormDataEntityExt.getDataId()) == null ? new JSONObject() : formDataMap.get(paasFormDataEntityExt.getDataId());
                paasFormDataEntityExt.setSubFormData(jsonObject);
                InactiveRuleDTO inactiveRuleDTO = new InactiveRuleDTO(businessRuleList, paasFormDataEntityExt, explainList,
                        paasFormDataEntityExt.getDataId(), inactiveRuleByDeleteBatchDTO.getBusinessType(), inactiveRuleByDeleteBatchDTO.getSaasMark(), corpid, inactiveRuleByDeleteBatchDTO.getLoginUser(),
                        inactiveRuleByDeleteBatchDTO.getPlatform(), inactiveRuleByDeleteBatchDTO.getHttpHeader(), inactiveRuleByDeleteBatchDTO.getBrowserInfo(), inactiveRuleByDeleteBatchDTO.getIp(), inactiveRuleByDeleteBatchDTO.getLocale(), 0);

                formDataInactiveRuleHelp.inactiveRuleBatch(inactiveRuleDTO);
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("formDataInactiveRuleByDeleteBatchHelp.validateDataByInactiveRule失效规则校验失败：", e);
        }
    }
}
